package com.zxq.factory.encoder.impl;

import com.zxq.factory.FastFrame;
import com.zxq.factory.encoder.IFieldEncoder;
import com.zxq.factory.model.CPTimeFrame;
import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CPTimeFieldEncoder implements IFieldEncoder<String> {

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @SneakyThrows
    @Override
    public byte[] encoder(String value, int len) {
        Date date =  df.parse(value);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        Integer year = calendar.get(Calendar.YEAR) - 2000;
        Integer month = calendar.get(Calendar.MONTH) + 1;
        Integer day = calendar.get(Calendar.DAY_OF_MONTH);
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY) ;
        Integer minute = calendar.get(Calendar.MINUTE);
        Integer second = ((calendar.get(Calendar.SECOND) + 65536) % 66536) * 1000 - 65536;

        CPTimeFrame cpTimeFrame = new CPTimeFrame();
        cpTimeFrame.setYear(year);
        cpTimeFrame.setMonth(month);
        cpTimeFrame.setDay(day);
        cpTimeFrame.setHour(hour);
        cpTimeFrame.setMinute(minute);
        cpTimeFrame.setSeconds(second);
        byte[] srcFrame = FastFrame.encoder(cpTimeFrame);
        byte[] dst = new byte[srcFrame.length];
        for(int i = 0; i < dst.length;i++) {
            dst[i] = srcFrame[srcFrame.length - i - 1];
        }

        return dst;
    }

}
